<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>淘好货 - 我的订单</title>
    <script src="/static/css/tailwindcss.css"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#FF4400', // 主色调：橙色
                        secondary: '#FFB800', // 辅助色：黄色
                        dark: '#333333',    // 深色文本
                        light: '#F5F5F5',   // 浅色背景
                        muted: '#666666',   // 次要文本
                        success: '#00B42A', // 成功色
                        warning: '#FF7D00', // 警告色
                        danger: '#F53F3F',  // 危险色
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif']
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .order-status-pill {
                @apply inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium;
            }

            .btn-active {
                @apply bg-primary text-white;
            }

            .btn-inactive {
                @apply hover:bg-gray-50;
            }
        }
    </style>
</head>
<body class="bg-gray-50 text-dark">
<div id="app">
    <!-- 导航栏 -->
    <navigation></navigation>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-8">
        <!-- 订单列表 -->
        <div class="lg:col-span-4">
            <div class="bg-white rounded-xl shadow-md mb-8">
                <div class="px-6 py-4 border-b border-gray-100 flex flex-wrap justify-between items-center">
                    <h2 class="text-xl font-bold">我的订单</h2>

                    <div class="flex flex-wrap gap-2 mt-3 md:mt-0">
                        <button class="px-4 py-2 text-sm font-medium rounded-lg"
                                :class="statusFilter === 'all' ? 'btn-active' : 'btn-inactive'"
                                @click="updateStatusFilter('all')">
                            全部订单
                        </button>
                        <button class="px-4 py-2 text-sm font-medium rounded-lg"
                                :class="statusFilter === '待支付' ? 'btn-active' : 'btn-inactive'"
                                @click="updateStatusFilter('待支付')">
                            待支付
                        </button>
                        <button class="px-4 py-2 text-sm font-medium rounded-lg"
                                :class="statusFilter === '待发货' ? 'btn-active' : 'btn-inactive'"
                                @click="updateStatusFilter('待发货')">
                            待发货
                        </button>
                        <button class="px-4 py-2 text-sm font-medium rounded-lg"
                                :class="statusFilter === '待收货' ? 'btn-active' : 'btn-inactive'"
                                @click="updateStatusFilter('待收货')">
                            待收货
                        </button>
                        <button class="px-4 py-2 text-sm font-medium rounded-lg"
                                :class="statusFilter === '已完成' ? 'btn-active' : 'btn-inactive'"
                                @click="updateStatusFilter('已完成')">
                            已完成
                        </button>
                    </div>
                </div>

                <!-- 订单筛选 -->
                <div class="px-6 py-4 border-b border-gray-100 flex flex-wrap gap-4 items-center">
                    <div class="relative w-full md:w-auto flex-1 md:flex-initial">
                        <input type="text" placeholder="搜索订单号"
                               v-model="orderNumber"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                    </div>

                    <div class="flex items-center space-x-2">
                        <label class="text-sm text-muted">时间范围:</label>
                        <select v-model="timeRange"
                                class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                            <option value="one_month">近一个月</option>
                            <option value="three_months">近三个月</option>
                            <option value="six_months">近半年</option>
                            <option value="">全部时间</option>
                        </select>
                    </div>

                    <button class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
                            @click="fetchOrders">
                        搜索
                    </button>
                </div>

                <!-- 加载状态 -->
                <div v-if="loading" class="py-16 flex justify-center items-center">
                    <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
                </div>

                <!-- 空状态 -->
                <div v-else-if="orders.length === 0" class="py-16 flex flex-col items-center">
                    <img src="/static/img/empty.png" alt="暂无订单" class="w-32 h-32 opacity-30">
                    <p class="mt-4 text-muted">暂无订单记录</p>
                    <button class="mt-4 px-6 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
                            @click="goToIndex">
                        立即购物
                    </button>
                </div>

                <!-- 订单列表 -->
                <div v-else class="divide-y divide-gray-100">
                    <div v-for="order in orders" :key="order.order_id" class="px-6 py-5">
                        <div class="flex flex-wrap justify-between items-center mb-4">
                            <div class="text-sm text-muted">
                                订单号: {{ order.order_number }}
                                <span class="ml-4">{{ order.created_at }}</span>
                            </div>
                            <span class="order-status-pill"
                                  :class="{
                                      'bg-primary/10 text-primary': order.order_status === '待支付',
                                      'bg-warning/10 text-warning': order.order_status === '待发货' || order.order_status === '待收货',
                                      'bg-success/10 text-success': order.order_status === '已完成' || order.order_status === '已支付',
                                      'bg-danger/10 text-danger': order.order_status === '已取消'
                                  }">
                                <i class="fa"
                                   :class="{
                                       'fa-clock-o': order.order_status === '待支付',
                                       'fa-truck': order.order_status === '待发货' || order.order_status === '待收货',
                                       'fa-check-circle': order.order_status === '已完成' || order.order_status === '已支付',
                                       'fa-times-circle': order.order_status === '已取消'
                                   }"></i>
                                {{ order.order_status }}
                            </span>
                        </div>

                        <div class="bg-gray-50 rounded-lg p-4 mb-4">
                            <div class="divide-y divide-gray-100">
                                <div v-for="product in order.products" :key="product.id" class="flex py-4">
                                    <img :src="product.image || 'https://picsum.photos/200/200?random=' + product.id"
                                         alt="商品图片"
                                         class="w-16 h-16 object-cover rounded-md">
                                    <div class="ml-4 flex-1">
                                        <h3 class="text-sm font-medium text-gray-900 line-clamp-2">{{ product.name }}</h3>
                                    </div>
                                    <div class="ml-4 text-right">
                                        <div class="font-medium">¥{{ product.price.toFixed(2) }}</div>
                                        <div class="text-xs text-muted">x{{ product.quantity }}</div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="flex flex-wrap justify-between items-center">
                            <div class="text-sm">
                                <span class="text-muted">实付款:</span>
                                <span class="font-bold text-primary">¥{{ order.total_amount.toFixed(2) }}</span>
                            </div>

                            <div class="flex flex-wrap gap-2 mt-3 md:mt-0">
                                <button v-if="order.order_status === '待支付'"
                                        class="px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90 transition-colors"
                                        @click="payOrder(order.order_id)">
                                    立即支付
                                </button>
                                <button v-if="order.order_status === '待发货'"
                                        class="px-4 py-2 border border-gray-300 rounded-lg text-sm hover:bg-gray-50 transition-colors"
                                        @click="cancelOrder(order.order_id)">
                                    取消订单
                                </button>
                                <button v-if="order.order_status === '待收货'"
                                        class="px-4 py-2 border border-gray-300 rounded-lg text-sm hover:bg-gray-50 transition-colors"
                                        @click="checkLogistics(order.order_id)">
                                    查看物流
                                </button>
                                <button v-if="order.order_status === '已完成'"
                                        class="px-4 py-2 border border-gray-300 rounded-lg text-sm hover:bg-gray-50 transition-colors"
                                        @click="buyAgain(order.order_id)">
                                    再次购买
                                </button>
                                <button v-if="order.order_status === '已完成'"
                                        class="px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90 transition-colors"
                                        @click="reviewProduct(order.order_id)">
                                    评价商品
                                </button>
                                <button
                                        class="px-4 py-2 border border-gray-300 rounded-lg text-sm hover:bg-gray-50 transition-colors"
                                        @click="viewDetails(order.order_id)">
                                    查看详情
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 分页 -->
                <div v-if="pagination.total_pages > 1"
                     class="px-6 py-5 flex justify-between items-center border-t border-gray-100">
                    <div class="text-sm text-muted">
                        共{{ pagination.total_items }}条订单
                    </div>

                    <div class="flex space-x-1">
                        <button :disabled="pagination.current_page === 1"
                                @click="goToPage(pagination.current_page - 1)"
                                class="w-10 h-10 flex items-center justify-center rounded-lg border border-gray-300 text-muted hover:bg-gray-50 opacity-50"
                                :class="{ 'opacity-50 cursor-not-allowed': pagination.current_page === 1 }">
                            <i class="fa fa-chevron-left"></i>
                        </button>

                        <button v-for="page in pagination.total_pages"
                                :key="page"
                                :class="{ 'bg-primary text-white': page === pagination.current_page }"
                                class="w-10 h-10 flex items-center justify-center rounded-lg border border-gray-300 hover:bg-gray-50"
                                @click="goToPage(page)">
                            {{ page }}
                        </button>

                        <button :disabled="pagination.current_page === pagination.total_pages"
                                @click="goToPage(pagination.current_page + 1)"
                                class="w-10 h-10 flex items-center justify-center rounded-lg border border-gray-300 text-muted hover:bg-gray-50 opacity-50"
                                :class="{ 'opacity-50 cursor-not-allowed': pagination.current_page === pagination.total_pages }">
                            <i class="fa fa-chevron-right"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer></footer>
</div>

<script src="/static/js/vue.js"></script>
<script src="/static/js/top.js"></script>
<script src="/static/js/foot.js"></script>
<script src="/static/js/common.js"></script>
<script src="/static/js/message.js"></script>
<script>
    // Vue实例
    new Vue({
        el: '#app',
        data: {
            util,
            orders: [],
            pagination: {
                current_page: 1,
                page_size: 10,
                total_pages: 1,
                total_items: 0
            },
            loading: false,
            orderNumber: '',
            timeRange: '',
            statusFilter: '',
        },
        mounted() {
            util.store.set("return-url", location.href);
            if (this.util.isLogin()) {
                this.fetchOrders();
            } else location.href = '/login';
        },
        methods: {
            // 获取订单列表
            async fetchOrders() {
                this.loading = true;

                try {
                    // 构建查询参数
                    const params = new URLSearchParams();
                    params.append('page', this.pagination.current_page);
                    params.append('page_size', this.pagination.page_size);

                    if (this.orderNumber) params.append('order_number', this.orderNumber);
                    if (this.timeRange) params.append('time_range', this.timeRange);
                    if (this.statusFilter) params.append('status', this.statusFilter);

                    // 发送请求
                    const response = await fetch(`/orders?${params.toString()}`);

                    if (!response.ok) {
                        const error = await response.json();
                        message.error(error.message)
                    }

                    const res = await response.json();
                    this.orders = res.data;
                    this.pagination = res.pagination;
                } catch (error) {
                    message.error("网络错误，请稍后重试");
                } finally {
                    this.loading = false;
                }
            },

            // 更新状态筛选
            updateStatusFilter(status) {
                this.statusFilter = status;
                this.pagination.current_page = 1; // 重置页码
                this.fetchOrders();
            },

            // 切换页码
            goToPage(page) {
                if (page >= 1 && page <= this.pagination.total_pages) {
                    this.pagination.current_page = page;
                    this.fetchOrders();
                }
            },

            // 支付订单
            payOrder(orderId) {
                console.log(`支付订单: ${orderId}`);
                // 实现支付逻辑
                window.location.href = `/pay?order_id=${orderId}`;
            },

            // 取消订单
            async cancelOrder(orderId) {
                if (confirm('确定要取消此订单吗？')) {
                    console.log(`取消订单: ${orderId}`);
                    // 实现取消订单逻辑
                    try {
                        const response = await fetch(`/orders/${orderId}`, {
                            method: 'DELETE',
                        });
                        if (!response.ok) {
                            const error = await response.json();
                            message.error(error.message);
                        } else {
                            await this.fetchOrders();
                        }
                    } catch (error) {
                        message.error('网络错误，请稍后重试');
                    }
                }
            },

            // 查看物流
            checkLogistics(orderId) {
                console.log(`查看物流: ${orderId}`);
                // 实现查看物流逻辑
            },

            // 再次购买
            buyAgain(orderId) {
                console.log(`再次购买: ${orderId}`);
                // 实现再次购买逻辑
            },

            // 评价商品
            reviewProduct(orderId) {
                console.log(`评价商品: ${orderId}`);
                // 实现评价商品逻辑
            },

            // 查看详情
            viewDetails(orderId) {
                console.log(`查看详情: ${orderId}`);
                // 实现查看详情逻辑
                 window.location.href = `/order-detail?order_id=${orderId}`;
            },
            // 跳转首页
            goToIndex() {
                window.location.href = '/';
            },
        }
    });
</script>
</body>
</html>